package com.wzf.greattruth.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * 
 * @author wuzhengfei
 *
 */
public class ClientWriteCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

	private AsynchronousSocketChannel asynSocketChannel;
	private CountDownLatch latch;

	public ClientWriteCompletionHandler(AsynchronousSocketChannel asynSocketChannel, CountDownLatch latch) {
		super();
		this.asynSocketChannel = asynSocketChannel;
		this.latch = latch;
	}

	@Override
	public void completed(Integer result, ByteBuffer buffer) {
		if (buffer.hasRemaining()) {
			asynSocketChannel.write(buffer, buffer, this);
		} else {
			ByteBuffer readBuffer = ByteBuffer.allocate(1024);
			asynSocketChannel.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
				@Override
				public void completed(Integer result, ByteBuffer buffer) {
					buffer.flip();
					byte[] bytes = new byte[buffer.remaining()];
					buffer.get(bytes);
					String body;
					try {
						body = new String(bytes, "UTF-8");
						System.out.println("Now is : " + body);
						latch.countDown();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void failed(Throwable exc, ByteBuffer attachment) {
					try {
						asynSocketChannel.close();
						latch.countDown();
					} catch (IOException e) {
						// ingnore on close
					}
				}
			});
		}
	}

	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		try {
			asynSocketChannel.close();
			latch.countDown();
		} catch (IOException e) {
			// ingnore on close
		}
	}

}
